<?php
namespace app\api\controller;

use think\Controller;
use think\Db;
use app\api\model\EbookCode;
use app\api\model\User;
use app\api\model\Ebook;
use app\api\model\EbookPrice;
/**
 *  微信
 */
class Wx extends Controller
{
	public function getWxAccessToken($code='')
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx2983f00cf3822439&secret=1d573777fa1096b03a650401dd5e659a&code=$code&grant_type=authorization_code";
        $res = http_curl($url, 'get');
        if(isset($res['openid'])) {
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$res['access_token']."&openid=".$res['openid']."&lang=zh_CN";
            $resnew = http_curl($url, 'get');
            // if()
            // 缓存access_token
            json_success($resnew);
        } else {
            json_success('暂无信息!');
        }
    }

    public function sendPost($str="")
    {
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        $res = $this->postXmlCurl($str,$url);
        json_success($res);
    }

    public function getUserInfo()
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=";
        $res = http_curl($url, 'get');
        if(isset($res['openid'])) {
            // 缓存access_token
            json_success(['openid'=>$res['openid'],'access_token'=>$res['access_token']]);
        } else {
            json_success('暂无信息!');
        }
    }

    public function test()
    {
    	$user = Db('user')->where(['old_nickname'=>"Tivon"])->find();
    	json_success($user);
    }

    public function add_ebookcode()
    {
        $num = input('num');
        $eid = input('eid');
        $openid = input('openid');
        $nickname = input('nickname');
        $gender = input('sex');
        $language = input('language');
        $city = input('city');
        $province = input('province');
        $country = input('country');
        $avatar_url = input('headimgurl');
        $user = Db('user')->where(['openid'=>$openid])->find();
        if(!$user) {
            // 创建用户
            $data = [
                'source_type'=>1,
                'source_id'=>0,
                'authorization'=>1,
                'is_mobile'=>2,
                'is_vip'=>2,
                'mobile'=>0,
                'openid'=>$openid,
                'create_time'=>time(),
                'old_nickname'=>$nickname,
                'gender'=>$gender,
                'city'=>$city,
                'language'=>$language,
                'province'=>$province,
                'country'=>$country,
                'avatar_url'=>$avatar_url,
                'status'=>1,
            ];
            Db('user')->insert($data);
            $userId = Db('user')->getLastInsID();
        } else {
            $userId = $user['id'];
        }
        for ($i=0; $i < $num; $i++) { 
            $map = [
                'uid'=>$userId ,
                'code'=>$this->getRandomString(10),
                'eid'=>$eid,
                'status'=>1
            ];
            $EbookCode = new \app\api\model\EbookCode();
            $EbookCode->allowField(true)->save($map);
        } 
    }

    public function ebook_list()
    {
        $data = [];
        // 推荐的三个
        $list=Db('ebook')->field('id,title,image,base_hits')->where("status=1")->order('sort desc,create_time desc')->select();
        // var_dump($data['top']);exit();
        if($list) {
            foreach ($list as $key => $value) {
                $list[$key]['views'] = $this->formatNum(Db('ebook_code')->where('eid',$value['id'])->count()+$list[$key]['base_hits']);
                $price = Db('ebook_price')->where(['eid'=>$value['id']])->order("price asc")->find();
                $list[$key]['price'] = isset($price)?$price['price']:0;
                // if(count($data['top'])<3) {
                //     $data['top'][] = $list[$key];
                // }
                $data[] = $list[$key];
            }
        }
        if (!empty($data)){
            json_success($data);
        }
        json_success([]);
    }

    public function ebook_price($id='')
    {
        $data = [];
        $data = Db('ebook_price')->field('price,num')->where("eid=$id")->order('price desc')->select();
        if (!empty($data)){
            json_success($data);
        }
        json_success([]);
    }

    public function getRandomString($len, $chars=null)  
    {  
        if (is_null($chars)) {  
            $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";  
        }  
        mt_srand(10000000*(double)microtime());  
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++) {  
            $str .= $chars[mt_rand(0, $lc)];  
        }  
        return $str;  
    } 

    public function ebook_code_list()
    {
        $openid=input('openid','');
        $user = Db('user')->where(['openid'=>$openid])->find();

        $page=input('page',1);
        $limit=input('limit',15);
        $status['status']=['eq',1];

        $data['list']=Db('ebook_code')->field('id,code,is_use,eid')->where($status)->where(['uid'=>$user['id']])->order('create_time desc')->page($page,$limit)->select();
        $data['count']=Db('ebook_code')->where(['uid'=>$user['id']])->where($status)->count();
        if($data['list']) {
            foreach ($data['list'] as $key => $value) {
                $data['list'][$key]['ebook'] = [];
                $obj = Db('ebook')->where(['id'=>$value['eid']])->find();
                if($obj) {
                    $data['list'][$key]['ebook'] = [
                        'id'=>$obj['id'],
                        'title'=>$obj['title'],
                        'image'=>$obj['image'],
                    ];
                }
            }
        }
        if (!empty($data)){
            json_success($data);
        }
        json_success([]);
    }

    /**
     * @param int $length
     * @return string
     * 格式化数字显示
     */
    public static function formatNum($num=0)
    {
        if($num<10000) {
            return $num;
        } elseif ($num>=10000&&$num<100000000) {
            return round($num/10000,2).'万';
        } else {
            return round($num/100000000,2).'亿';
        }
    }

    public function callback()
    {
        # code...
    }

    public function postXmlCurl($xml, $url, $useCert = false, $second = 30)
    {       
        $ch = curl_init();
        $curlVersion = curl_version();
        // $ua = "WXPaySDK/".self::$VERSION." (".PHP_OS.") PHP/".PHP_VERSION." CURL/".$curlVersion['version']." "
        // .$config->GetMerchantId();

        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);

        $proxyHost = "0.0.0.0";
        $proxyPort = 0;
        // $config->GetProxy($proxyHost, $proxyPort);
        //如果有配置代理这里就设置代理
        // if($proxyHost != "0.0.0.0" && $proxyPort != 0){
        //     curl_setopt($ch,CURLOPT_PROXY, $proxyHost);
        //     curl_setopt($ch,CURLOPT_PROXYPORT, $proxyPort);
        // }
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//严格校验
        // curl_setopt($ch,CURLOPT_USERAGENT, $ua); 
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if($data){
            curl_close($ch);
            return $data;
        } else { 
            $error = curl_errno($ch);
            curl_close($ch);
            throw new WxPayException("curl出错，错误码:$error");
        }
    }


}